package com.sam.mooc;

/**
 * Created by samwang on 2017/11/19.
 */
import java.net.URL;
import java.io.*;
import java.util.Date;

class Downloader
{
    static int count;
    public static void main(String[] args)
            throws Exception
    {
        final URL[] urls = {
                new URL("http://www.pku.edu.cn"),
                new URL("http://www.baidu.com"),
                new URL("http://www.sina.com.cn"),
                new URL("http://www.dstang.com")
        };
        final String[] files = {
                "pku.htm",
                "baidu.htm",
                "sina.htm",
                "study.htm",
        };

        Date startDate = new Date();
        count = urls.length;
        for(int idx=0; idx<urls.length; idx++){
            final int index = idx;
            new Thread(() -> {
                try{
                    System.out.println( urls[index] );
                    download( urls[index], files[index]);
                    count--;
                    if (count == 0) {
                        Date endDate = new Date();
                        System.out.println("use time: " + (endDate.getTime() - startDate.getTime()) + " ms");
                    }
                }catch(Exception ex){
                    ex.printStackTrace();
                }
            }).start();

        }


    }
    static void download( URL url, String file)
            throws IOException
    {
        try(InputStream input = url.openStream();
            OutputStream output = new FileOutputStream(file))
        {
            byte[] data = new byte[1024];
            int length;
            while((length=input.read(data))!=-1){
                output.write(data,0,length);
            }
        }
    }
}